package online.inote.naruto.spring.web.controller;

import lombok.extern.slf4j.Slf4j;
import online.inote.naruto.annotation.token.WebSecurity;
import online.inote.naruto.cache.CacheSupport;
import online.inote.naruto.security.utils.JwtHelper;
import online.inote.naruto.spring.web.entity.UserEntity;
import online.inote.naruto.utils.Assert;
import online.inote.naruto.utils.time.Calculator;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @description 用户Controller
 * @author gaopengsui@creditease.cn
 * @date 2021/10/20 6:31 下午
 */
@Slf4j
@RestController
@RequestMapping(value = "user")
public class UserController extends BaseController {

  @PostMapping(value = "login")
  @WebSecurity(required = false)
  public String login(@RequestBody UserEntity user) {
    Assert.notBlank(user.getUsername(), "Username cannot be null");
    Assert.notBlank(user.getPassword(), "Password cannot be null");

    // TODO 登录验证逻辑不在此实现，各系统自行实现，此处默认模拟登录成功
    // 默认用户名即为ID
    user.setId(user.getUsername());

    return tokenHandle(user);
  }

  public String tokenHandle(UserEntity user) {
    user.setPrivateKey(UUID.randomUUID().toString());

    String token =
        JwtHelper.genToken(user.getId(), user.getUsername(), null, Calculator.getNowDate());

    CacheSupport.cache(props.getCache().getPrefix() + user.getId(), token);

    return token;
  }

  @GetMapping(value = "info")
  public UserEntity info() {
    String id = getUserId();

    // TODO 模拟数据
    UserEntity user = new UserEntity();
    user.setId(id);
    user.setUsername(id);

    return user;
  }
}
